package com.hung.tripleregistry.controller;

import com.hung.tripleregistry.controller.annotation.PermissionLimit;
import com.hung.tripleregistry.core.model.RpcAdminRegistryRequest;
import com.hung.tripleregistry.core.model.RpcAdminRegistryResponse;
import com.hung.tripleregistry.service.RpcRegistryService;
import com.hung.tripleregistry.util.GsonTool;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;

/**
 * @author Hung
 * @date 2022/10/3 21:30
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    @Resource
    private RpcRegistryService rpcRegistryService;

    @RequestMapping("/{uri}")
    @PermissionLimit(limit = false)
    public Object api(@PathVariable("uri") @NotBlank String uri, @RequestBody(required = false) String data) {

        // services mapping
        switch (uri) {
            case "registry": {
                /*
                  服务注册 & 续约 API
                  说明：新服务注册上线1s内广播通知接入方；需要接入方循环续约，否则服务将会过期（三倍于注册中心心跳时间）下线；
                 */
                RpcAdminRegistryRequest registryRequest = GsonTool.fromJson(data, RpcAdminRegistryRequest.class);
                return rpcRegistryService.registry(registryRequest);
            }
            case "remove": {
                /*
                  服务摘除 API
                  说明：新服务摘除下线1s内广播通知接入方；
                 */
                RpcAdminRegistryRequest registryRequest = GsonTool.fromJson(data, RpcAdminRegistryRequest.class);
                return rpcRegistryService.remove(registryRequest);
            }
            case "discovery": {
                /*
                  服务发现 API
                  说明：查询在线服务地址列表；
                 */
                RpcAdminRegistryRequest registryRequest = GsonTool.fromJson(data, RpcAdminRegistryRequest.class);
                return rpcRegistryService.discovery(registryRequest);
            }
            case "monitor": {
                /*
                  服务监控 API
                  说明：long-polling 接口，主动阻塞一段时间（三倍于注册中心心跳时间）；直至阻塞超时或服务注册信息变动时响应；
                 */
                RpcAdminRegistryRequest registryRequest = GsonTool.fromJson(data, RpcAdminRegistryRequest.class);
                return rpcRegistryService.monitor(registryRequest);
            }
            default:
                return new RpcAdminRegistryResponse(RpcAdminRegistryResponse.FAIL_CODE, "invalid request, uri-mapping(" + uri + ") not found.");
        }

    }

}
